import {
  Body,
  ALL,
  Controller,
  Post,
  Provide,
  Inject,
  Get,
  Query,
  Put,
  Patch,
  Del,
} from '@midwayjs/decorator';

import { BaseController, ERRCODE } from '../../../comm/controller';
import { CreateCartDto, UpdateCartDto, CartPageDto } from '../dto/cart';
import { CustomerCartService } from '../service/cart';

/**
 * info：封装数据 -- 联表查询 product、sku，并生成总价列
 * page：多次调用 info
 * add/update：事务 -- 新建/修改记录、更新 customer 的 cart 信息，最后调用 info 返回数据
 * delete：事务 -- 更新 customer 的 cart 信息，再删除记录
 */
@Provide()
@Controller('/mall/cart')
export class CustomerCartController extends BaseController {
  @Inject()
  customerCartService: CustomerCartService;

  @Post('/add')
  async add(@Body(ALL) cartItem: CreateCartDto) {
    try {
      const data = await this.customerCartService.add(cartItem);
      return this.ok({ cartItem: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Post('/delete')
  @Del('/delete')
  async delete(cartId: number) {
    try {
      await this.customerCartService.delete(cartId);
      return this.ok();
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Post('/update')
  @Put('/update')
  @Patch('/update')
  async update(@Body(ALL) cartItem: UpdateCartDto) {
    try {
      const data = await this.customerCartService.update(cartItem);
      return this.ok({ cart: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Get('/info')
  async info(@Query() id: number, @Query() customerId: number) {
    try {
      const data = await this.customerCartService.info(id);
      return this.ok({
        customerId: Number(customerId),
        cartItem: data,
      });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Get('/page')
  async page(@Query(ALL) pageOp: CartPageDto) {
    try {
      const { count, data } = await this.customerCartService.page(pageOp);
      return this.ok({
        customerId: Number(pageOp.customerId),
        cartList: data,
        hasMore: pageOp.start + pageOp.limit < count,
        count,
      });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }
}
